#include "StaticMesh.h"
#include "3DSLoader/StaticMeshData.h"
#include <iostream>

CStaticMesh::CStaticMesh(void)
{
	pInstance = NULL;
	LocalToWorld.setIdentity();
	Init();
}

CStaticMesh::~CStaticMesh(void)
{
}

bool CStaticMesh::CreateFromFile(std::string filename)
{
	CStaticMeshData TempData;
	SrcFileName = filename;
	TempData.CreateFromFile(SrcFileName.c_str());

	int iVertexCount = 0;
	int iIndexCount = 0;
	int iObjectCount = TempData.ModelObjects.size();
	for(int i=0; i<iObjectCount; i++)
	{
		iVertexCount += TempData.ModelObjects[i].VertexCount;
		iIndexCount += TempData.ModelObjects[i].VertexIndexCount;
	}
	//allocate vertexBuffer;
	pInstance->VertexCount = iVertexCount;
	pInstance->pVertexBuffer = new CVertex[iVertexCount];
	//allocate vertex indexBuffer;
	pInstance->VertexIndexCount = iIndexCount;
	pInstance->pTriangleIndex = new int[iIndexCount];

	int iCurIndex = 0;
	//fill vertexBuffer
	for(int iObjectIndex=0; iObjectIndex<iObjectCount; iObjectIndex++)
	{
		int CurProcessCount = TempData.ModelObjects[iObjectIndex].VertexCount;
		for(int iIndex=0; iIndex<CurProcessCount; ++iIndex)
		{
			pInstance->pVertexBuffer[iIndex+iCurIndex].Normal = TempData.ModelObjects[iObjectIndex].pNormalsBuffer[iIndex];
			pInstance->pVertexBuffer[iIndex+iCurIndex].Position = TempData.ModelObjects[iObjectIndex].pVertexBuffer[iIndex];
			pInstance->pVertexBuffer[iIndex+iCurIndex].UV = TempData.ModelObjects[iObjectIndex].pUVsBuffer[iIndex];
		}
		iCurIndex += CurProcessCount;
	}

	//fill indexBuffer
	iCurIndex = 0;
	for(int iObjectIndex=0; iObjectIndex<iObjectCount; iObjectIndex++)
	{
		memcpy(&(pInstance->pTriangleIndex[iCurIndex]), TempData.ModelObjects[iObjectIndex].pVertexIndexBuffer, sizeof(int)*TempData.ModelObjects[iObjectIndex].VertexIndexCount);
		iCurIndex += TempData.ModelObjects[iObjectIndex].VertexIndexCount;
	}
	if(iObjectCount>1)
	{
		//last index should add vertex offset
		for(int i=1; i<iObjectCount; ++i)
		{
			int iCurIndexOffset = TempData.ModelObjects[i-1].VertexIndexCount;
			int iCurVertexOffset = TempData.ModelObjects[i-1].VertexCount;
			for(int j=0; j<TempData.ModelObjects[i].VertexIndexCount; ++j)
			{
				pInstance->pTriangleIndex[j+iCurIndexOffset] += iCurVertexOffset;
			}
		}
	}

	return true;
}

void CStaticMesh::Init()
{
	if(!pInstance)
	{
		pInstance = new CKDop;
	}
}